﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;

namespace netCoreStudy.Attr
{
	/// <summary>
	/// 发生在鉴权之后，其他动作之前  // 最适合做缓存 
	/// </summary>
	public class MyResourceFilterAttribute : IResourceFilter
	{
		private readonly ILogger<MyResourceFilterAttribute> _logger;
		private readonly IMemoryCache _cache;

		public MyResourceFilterAttribute(ILogger<MyResourceFilterAttribute> logger,
			IMemoryCache cache
		)
		{
			_logger = logger;
			_cache = cache;
		}

		/// <summary>
		/// 发生在其他动作之前
		/// </summary>
		/// <param name="context"></param>
		/// <exception cref="NotImplementedException"></exception>
		public void OnResourceExecuting(ResourceExecutingContext context)
		{
			PathString requestPath = context.HttpContext.Request.Path;
			Console.WriteLine(requestPath);

			object o = _cache.Get(requestPath);
			if (o != null)
			{
				Console.WriteLine("在这返回缓存");
				context.Result = new OkObjectResult(o);
			}
		}

		/// <summary>
		/// 发生在其他动作之后
		/// </summary>
		/// <param name="context"></param>
		/// <exception cref="NotImplementedException"></exception>
		public void OnResourceExecuted(ResourceExecutedContext context)
		{
			// 如果有缓存,直接返回缓存 
			PathString requestPath = context.HttpContext.Request.Path;
			Console.WriteLine(requestPath);
			if (_cache.Get(requestPath) == null)
			{
				Console.WriteLine("在这存储缓存");
				IActionResult contextResult = context.Result;
				ObjectResult okObjectResult = contextResult as ObjectResult;
				object value = okObjectResult.Value;
				_cache.Set(requestPath, value);
			}
		}
	}
}